package service

import (
	ClickHouse "gin/database"
	"gin/model"
	"gin/types"
)

type TaskDelay struct {
}

func (d *TaskDelay) Count(req types.DelayCountReq) (res types.DelayCountRes, err error) {

	db := ClickHouse.DB.Model(&model.ReviewRequest{}).
		Joins("JOIN task on task.id = review_request.link_id").
		Where("JSONLength(JSONExtractString(task.json, 'task_deprecate_data')) = 0 and simpleJSONExtractInt(task.json,'task_status') <> 3")

	//延期任务 review_request created,created_by ->user->tenant_user[department_id]
	var module model.Module
	taskModule, err := module.GetByCode("task")
	if err != nil {
		return res, err
	}
	db.Where("review_request.module_id = ?", taskModule.Id)
	if req.ProjectId > 0 {
		db.Where("review_request.project_id = ?", req.ProjectId)
	}
	if req.StartTime > 0 {
		db.Where("review_request.created >= ?", req.StartTime)
	}
	if req.EndTime > 0 {
		db.Where("review_request.created <= ?", req.EndTime)
	}
	var userIdList []int64
	if req.DepartmentId > 0 {
		err = ClickHouse.DB.Model(&model.TenantUser{}).
			Joins("join user on user.union_id = tenant_user.user_id").
			Where("tenant_user.department_id = ?", req.DepartmentId).
			Distinct("user.id").Pluck("user.id", &userIdList).Error
		if err != nil || len(userIdList) == 0 {
			return res, err
		}
		db.Joins("JOIN task_member on task_member.task_id = review_request.link_id").
			Where("task_member.partner in ?", userIdList)
	}

	if len(req.TodoStepCategoryId) > 0 {
		db.Joins("join task_relation_tag r_step_category on r_step_category.task_id = task.id and r_step_category.link_module_code in ('step_category','show_step_category')").
			Where("r_step_category.link_id in ?", req.TodoStepCategoryId)
	}

	err = db.Select("count(review_request.id) Total,count(review_request.is_pass = 'yes') as Pass").Find(&res).Error

	res.NotPass = res.Total - res.Pass

	return
}
